import Taro from '@tarojs/taro'
import { MaterialIcons } from 'taro-icons';
import React, { useState, useEffect, useRef } from 'react';
import { View, Text, Picker, ScrollView } from '@tarojs/components';

import DataErrorView from '../../components/dataError';
import EmptyContent from '../../components/emptyContent';
import { NoticeResponseItem } from '../../types/service';
import { useAppContext } from '../../contexts/AppContext';
import DataLoadingView from '../../components/dataLoading';
import { getToken, userLoginLimit } from '../../contexts/store';
import CityBaseList from '../../components/basePage/CityBaseList';
import { calculateGeoDistance } from '../../utils/coordTransform';
import NoticeMessage from '../../components/basePage/noticeMessage';
import ProvinceCitySelector from '../../components/ProvinceCitySelector.js';
import HotLocationsBanner from '../../components/basePage/HotLocationsBanner';

import { getNoticeMessageApi } from '../../api/service';
import { setUserLocationApi, getUserLocationApi } from '../../api/user';
import { getChinaCityListApi, getCityInfoByLocationApi } from '../../api/cityApi';
import { getBaseLicensesApi, getBaseTrafficApi, getBasesByCityApi } from '../../api/baseApi';
import type { CityBaseItem, cityDistrictItem, RegionNode, baseTrafficItem } from '../../types/cityBase';


import './index.scss';

const Home: React.FC = () => {
  // 获取全局状态
  const {
    userLocation,
    selectedRegionPath, 
    setSelectedRegionPath, 
    selectedNode,        
    setSelectedNode,
    selectedParentNode,  
    setSelectedParentNode,
    selectedDistrict: appSelectedDistrict,
    setSelectedDistrict,
    setUserLocation,
    setSelectedCityBaseData
  } = useAppContext();
  
  // 通知消息状态
  const hasFetched = useRef(false);
  const [cityId, setCityId] = useState<string>('');
  const [loading, setLoading] = useState<boolean>(false);
  const [error, setError] = useState<string | null>(null);
  const [cityBaseList, setCityBaseList] = useState<CityBaseItem[]>([]);
  const [allCityBaseList, setAllCityBaseList] = useState<CityBaseItem[]>([]);
  const [noticeMessages, setNoticeMessages] = useState<NoticeResponseItem[]>([]);
  const [baseLicenses, setBaseLicenses] = useState<{[key: string]: string[]}>({});
  const [baseTrafficList, setBaseTrafficList] = useState<{[key: number]: baseTrafficItem}>({});

  // 收起筛选/筛选
  const [showFilters, setShowFilters] = useState(false);
  // 城市树数据源
  const [chinaRegions, setChinaRegions] = useState<RegionNode[]>([]);
  // 设置三级行政区信息
  const [cityDistricts, setCityDistricts] = useState<cityDistrictItem[]>([]);
  // 距离筛选选项
  const areaDistance: number[] = [0,3, 5, 10, 15, 20];
  // 定位失败提示状态
  const [showLocationError, setShowLocationError] = useState(false);
  // 定位加载状态
  const [locationLoading, setLocationLoading] = useState(false);
  // 定位错误信息
  const [locationError, setLocationError] = useState<string>('');
  // 当前城市名称
  const [currentCity, setCurrentCity] = useState<string>('');
  const sortTypes = [
    { label: '智能排序', value: 'smart' },
    { label: '距离优先', value: 'distance' },
    { label: '口碑优先', value: 'rating' },
    { label: '合格率优先', value: 'passRate' }
  ]
  const [filterBase, setFilterBase] = useState<{
    district?: number;
    distanceRange?: number;
    sortType?: string;
  }>({
    district: 0,
    distanceRange: 0,
    sortType: 'smart'
  });

  // 处理行政区变更
  const handleDistrictChange = (district: cityDistrictItem) => {
    if (district.id == 0) {
      if (selectedNode?.level == 1) {
        setSelectedRegionPath([selectedRegionPath[0], selectedNode.id.toString()]);
        setSelectedDistrict(selectedNode.name);
      }else if (selectedNode?.level == 2) {
        setSelectedNode(selectedParentNode);
        setSelectedDistrict(selectedParentNode?.name || '');
        setSelectedRegionPath([selectedRegionPath[0], selectedParentNode?.id.toString() || '']);
      }
    }else{
      setSelectedRegionPath([...district.parents, district.id.toString()]);
      setSelectedDistrict(district.name);
      if (selectedNode?.level == 1) {
        setSelectedParentNode(selectedNode);
        selectedNode?.children?.forEach((item: RegionNode) => {
          if (item.id == district.id) {
            setSelectedNode(item);
          }
        })
      } else if (selectedNode?.level == 2) {
        selectedParentNode?.children?.forEach((item: RegionNode) => {
          if (item.id == district.id) {
            setSelectedNode(item);
          }
        })
      }
    }
  
    setFilterBase({
      ...filterBase,
      district: district.id
    });
    filterSort(filterBase.distanceRange || 0, filterBase.sortType || 'smart', district.id);
  };

  // 处理地区选择变更
  const handleRegionSelect = (path: string[], node?: RegionNode, parentNode?: RegionNode | null) => {
    setFilterBase({
      ...filterBase,
      district: 0,
      distanceRange: 0,
    });
    setSelectedDistrict('');
    setSelectedRegionPath(path);
    if (node) {
      setSelectedNode(node);
      if (parentNode !== undefined) {
        setSelectedParentNode(parentNode);
      }
    }
  };
  
  const setDefaultCityBaseData = (cityList: any[], city: string = "") => {
      // 设置默认地址为上海市
      const chinaCityList = cityList || chinaRegions;
      const cityName = city || '上海市';
      const shanghaiProvince = chinaCityList.find((province: any) => province.name === cityName) || cityList[0];
      if (shanghaiProvince) {
        const shanghaiCity = shanghaiProvince.children ? shanghaiProvince.children[0] : null;
        if (shanghaiCity) {
          const defaultPath = [shanghaiProvince.id.toString(), shanghaiCity.id.toString()];
          setSelectedRegionPath(defaultPath);
          setSelectedNode(shanghaiCity);
          // 设置默认的区县列表
          const districts = shanghaiCity.children ? shanghaiCity.children.map((item: any) => ({
            id: item.id,
            name: item.name,
            parents: [shanghaiProvince.id.toString(), shanghaiCity.id.toString()]
          })) : [];
          setCityDistricts(districts);
          updateBaseList(districts);
        }
      }
  }
  
  const updateUserLocation = async (location: any) => {
    if (!getToken()) {
      console.log("用户未登录，获取默认城市");
      return;
    }
    await setUserLocationApi(
      location.latitude,
      location.longitude,
      location.cityName,
      location.address,
      location.areaName,
      location.areaCode,
      location.cityCode,
    );
  }

  // 获取用户当前地理位置坐标
  const fetchUserLocation = (chinaRegionList: any[] = []) => {
    if (!userLoginLimit('获取个人位置信息，需登录服务'))  return;

    setShowLocationError(false);
    setLocationLoading(true);
    setLocationError('');
    const chinaCityList = chinaRegionList || chinaRegions;
    
    // 先检查用户的位置权限状态
    Taro.getSetting({
      success: (res) => {
        // 检查是否有位置权限
        if (!res.authSetting['scope.userFuzzyLocation']) {
          // 如果没有权限，请求授权
          Taro.authorize({
            scope: 'scope.userFuzzyLocation',
            success: () => {
              // 授权成功后获取位置
              getLocationWithFallback();
            },
            fail: (err) => {
              console.error('请求位置权限失败:', err);
              setLocationLoading(false);
              // 如果用户拒绝授权，提示用户并引导用户去设置页面打开权限
              Taro.showModal({
                title: '需要位置权限',
                content: '请授权位置权限以便获取您附近的驾校信息',
                confirmText: '去设置',
                success: (resModal) => {
                  if (resModal.confirm) {
                    // 跳转到设置页面
                    Taro.openSetting({
                      success: (resSetting) => {
                        if (resSetting.authSetting['scope.userFuzzyLocation']) {
                          // 用户在设置页面打开了权限，再次尝试获取位置
                          getLocationWithFallback();
                        } else {
                          setLocationError('定位失败');
                          setShowLocationError(true);
                          setDefaultCityBaseData(chinaCityList);
                        }
                      }
                    });
                  } else {
                    setLocationError('定位失败');
                    setShowLocationError(true);
                    setDefaultCityBaseData(chinaCityList);
                  }
                }
              });
            }
          });
        } else {
          // 已经有权限，直接获取位置
          getLocationWithFallback();
        }
      },
      fail: (err) => {
        console.error('获取设置失败:', err);
        setLocationLoading(false);
        setLocationError('定位失败');
        setShowLocationError(true);
        setDefaultCityBaseData(chinaCityList);
      }
    });
    
    // 统一的获取位置逻辑，带降级处理
    const getLocationWithFallback = () => {
      Taro.getFuzzyLocation({
        type: 'gcj02',
        success: (resp) => {
          const { latitude, longitude } = resp;
          console.log('获取到位置信息:', resp);
          // 调用逆地理编码API获取城市名称
          getCityInfoByLocationApi(latitude, longitude).then((res: any) => {
            console.log('获取到位置信息:', res);
            setLocationLoading(false);
            
            // 如果获取到位置信息，自动更新地区信息
            if (res && res.data && res.data.cityName) {
              const cityName = res.data.township || res.data.areaName;
              setUserLocation({
                latitude: latitude,
                longitude: longitude,
                cityCode: res.data.cityCode,
                cityName: res.data.cityName,
                areaCode: res.data.areaCode,
                areaName: res.data.areaName,
              })
              updateUserLocation({
                latitude: latitude,
                longitude: longitude,
                cityCode: res.data.cityCode,
                cityName: res.data.cityName,
                areaCode: res.data.areaCode,
                areaName: res.data.areaName,
                address: cityName,
              })
              // 更新当前城市
              setCurrentCity(cityName);
              console.log(`用户定位城市: township=${res.data.township}, areaName=${res.data.areaName}`);
              console.log("chinaRegions:", chinaRegions);
              for (const province of chinaRegions) {
                const city = province.children?.find(c => c.name.includes(res.data.cityName));
                console.log("用户定位城市:", city);
                if (city) {
                  const path = [province.id.toString(), city.id.toString()];
                  handleRegionSelect(path, city, province);
                  break;
                }
              }
            }else {
              setLocationError('定位失败');
              setLocationLoading(false);
              setDefaultCityBaseData(chinaCityList);
            }
          }).catch(error => {
            console.error('地理编码API错误:', error);
            setLocationLoading(false);
            setLocationError('定位失败');
            setShowLocationError(true);
            setDefaultCityBaseData(chinaCityList);
          });
        },
        fail: (err) => {
            console.error('获取位置失败:', err);
            setLocationLoading(false);
            setLocationError('定位失败');
            setShowLocationError(true);
            setDefaultCityBaseData(chinaCityList);
          }
        });
      };
  };

  const getUserLocation = async(data) => {
    if (!getToken()) {
      console.log("用户未登录，获取默认城市");
      setDefaultCityBaseData(data, '上海市');
      return;
    }
    console.log("用户已登录，获取用户位置");
    await getUserLocationApi().then((resp: any) => {
      if (resp.code == 200 && resp.data) {
        setUserLocation({
          latitude: resp.data.latitude,
          longitude: resp.data.longitude,
          cityCode: resp.data.cityCode,
          cityName: resp.data.city,
          areaCode: resp.data.areaCode,
          areaName: resp.data.area,
        })
        console.log("获取用户历史位置:", resp.data);
        setCurrentCity(resp.data.address);
        setDefaultCityBaseData(data, resp.data.city);
      }else{
        setDefaultCityBaseData(data, '上海市');
      }
    }).catch(error => {
      setDefaultCityBaseData(data, '上海市');
    })
  }

  const getNoticeMessage = async () => {
    getNoticeMessageApi().then((res: any) => {
      if (res.code == 200 && res.data) {
        setNoticeMessages(res.data);
      }
    }).catch(error => {
      console.error('获取通知消息失败:', error);
    })
  }

  // 处理过滤排序
  const handleFilterChange = (dataList: CityBaseItem[] = [], filterData: any = null) => {
    console.log('handleFilterChange', dataList, filterData);
    let filteredList: CityBaseItem[] = [];
    if (dataList && dataList.length > 0) {
      // 按照行政区过滤基地数据
      if (filterData.district === 0 || !filterData.district) {
        filteredList = dataList;
      } else {
        filteredList = dataList.filter((item: CityBaseItem) => {
          return item.city === filterData.district;
        });
      }

      if(userLocation?.longitude && userLocation?.latitude) {
        filteredList = filteredList.filter((item: CityBaseItem) => {
          return item.distance && item.distance <= filterData.distanceRange;
        });
      }

        // 排序基地数据
      let sortedList = [...filteredList];
      
      // 根据排序类型进行排序
      if (filterData.sortType === 'distance') {
        // 距离排序或smart模式且有用户位置数据时，按距离排序
        sortedList.sort((a, b) => {
          const distanceA = a.distance || 0;
          const distanceB = b.distance || 0;
          return distanceA - distanceB;
        });
      } else if (filterData.sortType === 'smart') {
        // smart模式排序：先按行政区排序，然后在行政区内部按距离排序
        sortedList.sort((a, b) => {
          // 先按行政区排序
          if (a.city && b.city) {
            const cityCompare = a.city - b.city;
            if (cityCompare !== 0) {
              return cityCompare;
            }
            // 同一行政区内按距离排序
            const distanceA = a.distance || 0;
            const distanceB = b.distance || 0;
            return distanceA - distanceB;
          }
          return 0;
        });
      }
      
      setCityBaseList(sortedList);
    }
  };

  // 获取城市基地列表
  const updateBaseList = async (districts: cityDistrictItem[]) => {
    try {
      setLoading(true);
      setError(null);
      const districtIdList = districts.map(district => district.id);
      console.log('获取城市基地列表: districts=', districtIdList);

      if (!districtIdList || districtIdList.length === 0) {
        setCityBaseList([]);
        setAllCityBaseList([]);
        setLoading(false);
        return;
      }

      const response = await getBasesByCityApi(districtIdList);
      if (response.code === 200 && response.data) {
        setAllCityBaseList(response.data);
        handleFilterChange(response.data, filterBase);
        console.log('成功获取到城市基地列表：', response.data);
        // 计算距离
        if (userLocation?.longitude && userLocation?.latitude) {
          response.data.forEach((base: CityBaseItem) => {
            base.distance = computeBaseDistance(base.latitude, base.longitude);
          });
        }
        setCityBaseList(response.data);
        setLoading(false);
        // 获取基地执照信息
        const baseIdList = response.data.map((base: CityBaseItem) => base.id);
        if (baseIdList && baseIdList.length > 0) {
          const licensesResponse = await getBaseLicensesApi(baseIdList);
          if (licensesResponse.code === 200 && licensesResponse?.data?.bases) {
            setBaseLicenses(licensesResponse.data.bases);
          }
          
          // 获取基地交通信息
          const trafficResponse = await getBaseTrafficApi(baseIdList);
          if (trafficResponse.code === 200 && trafficResponse.data) {
            setBaseTrafficList(trafficResponse.data);
          }
        }
      } else {
        setError(response.message || '获取基地列表失败');
      }
    } catch (err) {
      setError('获取驾照列表失败，请稍后重试。');
      console.error('获取驾照列表错误:', err);
    } finally {
      setLoading(false);
    }
  };

  const computeBaseDistance = (lat, lng) => {
    // 如果没有用户位置数据，按照0千米处理
    if (!userLocation?.longitude || !userLocation?.latitude || !lat || !lng) {
      return 0;
    }
    
    const { longitude, latitude } = userLocation;
    const userDistance: any = calculateGeoDistance(longitude, latitude, lng, lat);
    return userDistance?.distance || 0;
  }

  const filterSort = (distanceRange: number, sortType: string, district: number) => {
    handleFilterChange(allCityBaseList, 
      { 
        distanceRange: distanceRange, 
        sortType: sortType,
        district: district
      });
  }

  // 组件挂载时初始化
  useEffect(() => {
    if (hasFetched.current) {
      return;
    }
    hasFetched.current = true;
    setSelectedDistrict('');
    getChinaCityListApi().then((res: any) => {
      setChinaRegions(res.data);
      getUserLocation(res.data);
    });
    getNoticeMessage();
  }, []);

  // 根据选择的地区筛选驾校
  useEffect(() => {
    if (selectedRegionPath.length >= 2) {
      const newCityId = selectedRegionPath.length == 3 ? selectedRegionPath[2] : selectedRegionPath[1];
      if (newCityId) {
        let parentCityId: string = '';
        let city_districts: cityDistrictItem[] = [];
        if (selectedRegionPath.length == 3) {
          setFilterBase({ ...filterBase, district: selectedNode?.id || 0 });
          city_districts = selectedParentNode?.children?.map((item: any) => ({
            id: item.id, 
            name: item.name, 
            parents: [selectedRegionPath[0], selectedRegionPath[1]]
          })) || [];
          parentCityId = selectedParentNode?.id?.toString() || '';
        } else if (selectedRegionPath.length == 2) {
          city_districts = selectedNode?.children?.map((item: any) => ({
            id: item.id, 
            name: item.name, 
            parents: [selectedRegionPath[0], selectedNode.id.toString()]
          })) || [];
          parentCityId = selectedNode?.id?.toString() || '';
        }
        console.log(cityId, parentCityId)
        if (cityId !== parentCityId) {
          setCityId(newCityId);
          setCityDistricts(city_districts);
          updateBaseList(city_districts);
        }
      }
    }
  }, [selectedRegionPath]);

  // 渲染当前选中的城市信息
  const renderSelectedCityInfo = () => {
    if (!appSelectedDistrict && !selectedNode?.name) {
      return '选择地区';
    }
    return appSelectedDistrict || selectedNode?.name || '选择地区';
  };

  return (
    <View className='page-container home'>
      <View className='header'>
        <View className='header-left'>
          {/* 地区选择器 - 点击城市名称直接打开选择树 */}
          <MaterialIcons name="location-on" color="#1890ff" size={22} />
          <ProvinceCitySelector 
            level="city"
            chinaRegions={chinaRegions}
            onSelect={handleRegionSelect}
            selectedRegionPath={selectedRegionPath}
          >
            <View className='region-select-button'>
              <Text className='region-text'>{renderSelectedCityInfo()}</Text>
            </View>
          </ProvinceCitySelector>

        </View>
        <View className='header-right'>
          <View className='location-button-container'>
            <View className='my-location-button'
              onClick={() => fetchUserLocation()}
            >
              <MaterialIcons name="home" color="#1890ff" size={20} />
              <Text className='text-gray-500 mr-2' style={{fontSize: '24rpx'}}>我的位置：</Text>
              {locationLoading && (
                <Text className='location-loading-text'>定位中...</Text>
              )}
              <Text className={showLocationError ? 'error-text' : currentCity ? 'success-text' : ''}>
                {showLocationError ? '定位失败' : currentCity ? currentCity : ''}
              </Text>
            </View>
          </View>
        </View>
      </View>

      {/* 消息滚动条组件 */}
      {noticeMessages && noticeMessages.length > 0 && (
        <NoticeMessage messages={noticeMessages} />
      )}

      {/* 横幅 */}
      <HotLocationsBanner />

      {/* 排序选项 */}
      <View className="city-base-filter">
        <View className='filter-button'
          onClick={() => setShowFilters(!showFilters)}
        >
          <Text>
            {showFilters ? '收起筛选' : '筛选'}
          </Text>
        </View>
        <View>
          <Picker
            mode='selector'
            range={sortTypes.map(item => item.label)}
            value={sortTypes.findIndex(item => item.value == filterBase.sortType)}
            onChange={(e) => {
              const selectedIndex = e.detail.value;
              const sortType = sortTypes[selectedIndex].value as string;
              setFilterBase({ ...filterBase, sortType: sortType });
              filterSort(filterBase.distanceRange || 0, sortType, filterBase.district || 0);
            }}
          >
            <Text className='filter-button'>{sortTypes[0].label}</Text>
          </Picker>
        </View>
      </View>

      {/* 筛选条件区域 */}
      {showFilters && (
        <View className="filter-section bg-white p-4 shadow-sm">
          <View className="mb-4">
            {/* 距离筛选 */}
            <View className="mb-4">
              <Text className="text-gray-400 text-lg mb-2 block">范围</Text>
              <View className="flex flex-wrap gap-2">
                {areaDistance.map((range) => (
                  <View
                    key={range}
                    className={`tag-item ${filterBase.distanceRange === range ? 'tag-selected' : ''}`}
                    onClick={() => {
                      setFilterBase({ ...filterBase, distanceRange: range });
                      filterSort(range, filterBase.sortType || 'smart', filterBase.district || 0);
                    }}
                  >
                    <Text className={`tag-text ${filterBase.distanceRange === range ? 'tag-text-selected' : ''}`}>
                      {range == 0?'不限':`${range}km`}
                    </Text>
                  </View>
                ))}
              </View>
            </View>

            <View>
              <Text className="text-gray-400 text-lg mb-2 block">行政区</Text>
                <View style={{ paddingRight: '10px' }}>
                  {/* 增加"不限"选项，置于第一个 */}
                  { cityDistricts && cityDistricts.length > 0 && (
                    <View
                      key="unlimited"
                      className={`tag-item ${selectedRegionPath?.length === 2 ? 'tag-selected' : ''}`}
                      onClick={() => {
                        if (selectedRegionPath?.length >= 2) {
                          handleDistrictChange({
                            id: 0,
                            name: '不限',
                            parents: [],
                          });
                        }
                      }}
                    >
                      <Text className={`tag-text ${selectedRegionPath?.length === 2 ? 'tag-text-selected' : ''}`}>
                        不限
                      </Text>
                    </View>
                  )}

                  {/* 原有的行政区列表 */}
                  {cityDistricts?.map((district) => (
                    <View
                      key={district.id}
                      className={`tag-item ${selectedRegionPath?.length === 3 && district.id.toString() === selectedRegionPath[2] ? 'tag-selected' : ''}`}
                      onClick={() => handleDistrictChange(district)}
                    >
                      <Text className={`tag-text ${selectedRegionPath?.length === 3 && district.id.toString() === selectedRegionPath[2] ? 'tag-text-selected' : ''}`}>
                        {district.name}
                      </Text>
                    </View>
                  ))}
                </View>
            </View>
          </View>
        </View>
      )}

      {/* 基地列表 */}
      <ScrollView className="mt-2">
        {loading && (
          <DataLoadingView />
        )}
        {cityBaseList.length > 0 && (
          <CityBaseList 
            cityBaseList={cityBaseList}
            baseTrafficList={baseTrafficList}
            baseLicenses={baseLicenses}
            setSelectedCityBaseData={setSelectedCityBaseData}
          />
        )}

        {/* 空状态 */}
        {!loading && cityBaseList.length === 0 && (
          <EmptyContent title="暂无数据" />
        )}
        {/* 错误状态 */}
        {error && !loading && (
          <DataErrorView title="出错啦~" content={error} />
        )}
      </ScrollView>
    </View>
  );
};

export default Home;
